//
//  HTClassPurchaseVC.swift
//  QuitSmokingApp
//  
//  Created by wealon on 2024.
//  QuitSmokingApp.
//  133
    

import UIKit
import Foundation

class HTClassPurchaseVC: HTClassViewController {
    lazy var var_tableView: UITableView = {
        let var_tab = UITableView(frame: .zero, style: .plain)
        var_tab.bounces = false
        var_tab.dataSource = self
        var_tab.delegate = self
        var_tab.backgroundColor = .clear
        var_tab.tableHeaderView = self.var_tableHeaderView
        var_tab.sectionHeaderTopPadding = 0
        var_tab.register(HTClassSearchCell.self, forCellReuseIdentifier: "HTClassSearchCell")
        var_tab.register(HTClassDesCell.self, forCellReuseIdentifier: "HTClassDesCell")
        return var_tab
    }()
    var var_dataSource: [HTClassPurchaseModel] = []
    lazy var var_tableHeaderView: HTClassPurchaseHeadView = {
        let var_view = HTClassPurchaseHeadView(frame: .zero)
        var_view.isSubscribe = false
        return var_view
    }()
    lazy var var_right_button: UIButton = {
        let var_btn = UIButton()
        var_btn.setTitle("restore", for: .normal)
        var_btn.titleLabel?.font = .systemFont(ofSize: 16, weight: .bold)
        var_btn.setTitleColor(UIColor("#7230FF"), for: .normal)
        var_btn.onTap { [weak self] in
            //恢复购买
            var_btn.isEnabled = false
            let var_hud = HTClassHudView().ht_showLoadingOnView(var_view: self!.view, var_completedBlock: nil)
            var_HTClassPayManagerInstance.ht_restore { [weak self] var_isSuccess, var_isCancel, var_msg, var_purchaseInfo in
                DispatchQueue.main.async {
                    var_btn.isEnabled = true
                    var_hud.hide(animated: true, afterDelay: var_kHudHiddenTime)
                    if var_isSuccess {
                        HTClassHudView().ht_showToastOnView(var_view: self!.view, var_title: var_msg, var_completedBlock: nil).hide(animated: true, afterDelay: var_kHudHiddenTime)
                    }else{
                        if var_isCancel == false{
                            HTClassHudView().ht_showToastOnView(var_view: self!.view, var_title: var_msg, var_completedBlock: nil).hide(animated: true, afterDelay: var_kHudHiddenTime)
                        }
                    }
                    //刷新订阅信息
                    self?.ht_reloadPurchaseInfo()
                    //移除监听
                    var_HTClassPayManagerInstance.var_payResultBlock = nil
                }
            }
        }
        return var_btn
    }()
    
    var var_selectedProductid: String = ""
    deinit{
        var_HTClassPayManagerInstance.var_allProductsCallback = nil
        var_HTClassPayManagerInstance.var_payResultBlock = nil
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "premium"
        if let var_nav = self.navigationController as? HTClassNavigationController {
            var_nav.var_back.setImage(UIImage(named: "icon_r_back"), for: .normal)
        }
        //获取所有产品列表
        ht_getAllProducts()
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        if let var_nav = self.navigationController as? HTClassNavigationController {
            var_nav.var_back.setImage(UIImage(named: "icon_white_back"), for: .normal)
        }
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.setNavigationBarHidden(false, animated: true)
    }
    
    //获取所有产品列表
    func ht_getAllProducts(){
#warning("var_productIds记得修改对应产品id！！！！！")
        var_right_button.isEnabled = false
        let var_hud = HTClassHudView().ht_showLoadingOnView(var_view: self.view, var_completedBlock: nil)
        var_HTClassPayManagerInstance.ht_requestProducts(var_productIds: ["week", "month", "year"]) {[weak self] var_products in
            DispatchQueue.main.async {
                self?.var_right_button.isEnabled = true
                var_hud.hide(animated: true, afterDelay: var_kHudHiddenTime)
                for var_pro in var_products {
                    let var_numberFormatter = NumberFormatter()
                    var_numberFormatter.formatterBehavior = .behavior10_4
                    var_numberFormatter.numberStyle = .currency
                    var_numberFormatter.locale = var_pro.priceLocale
                    let var_formattedString = var_numberFormatter.string(from: var_pro.price)
                    self?.var_dataSource.append(HTClassPurchaseModel(var_title: var_pro.localizedTitle, var_price: var_formattedString ?? "0.0", var_productId: var_pro.productIdentifier))
                    //此处可以对产品list进行排序
                }
                self?.var_tableView.reloadData()
                //刷新订阅信息
                self?.ht_reloadPurchaseInfo()
            }
        }
    }
    
    //刷新订阅信息
    func ht_reloadPurchaseInfo(){
        let var_model = HTClassStorage.ht_getPurchaseInfo()
        self.var_tableHeaderView.isSubscribe = var_model!.var_isSubscribe
        if var_model!.var_isSubscribe {
            var var_name = ""
            for var_data in self.var_dataSource {
                if var_model?.var_productId == var_data.var_productId {
                    var_name = var_data.var_title
                }
            }
            self.var_tableHeaderView.var_titleLabel.text = var_name
        }
        self.var_tableView.reloadData()
    }
    
    override func ht_setUI() {
        super.ht_setUI()
        self.view.addSubview(var_tableView)
        var_tableView.snp.makeConstraints { make in
            make.left.equalToSuperview()
            make.right.equalToSuperview()
            make.bottom.equalToSuperview()
            make.top.equalToSuperview().offset(HTClassTool.STATIC_navigationBarTotalHeight + 20)
        }
        let var_item = UIBarButtonItem(customView: var_right_button)
        self.navigationItem.rightBarButtonItem = var_item
    }
}
extension HTClassPurchaseVC: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return var_dataSource.count + 1
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section < self.var_dataSource.count {
            return -1
        }
        return 250
    }
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 20
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView(frame: CGRect(x: 0, y: 0, width: HTClassTool.STATIC_screenWidth, height: 20))
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section < self.var_dataSource.count {
            let cell = tableView.dequeueReusableCell(withIdentifier: "HTClassSearchCell", for: indexPath) as! HTClassSearchCell
            let var_model = var_dataSource[indexPath.section]
            cell.var_nameLabel.text = var_model.var_title
            cell.var_priceLabel.text = var_model.var_price
            cell.var_IsCheak = var_selectedProductid == var_model.var_productId
            return cell
            
        } else {
            let cell = tableView.dequeueReusableCell(withIdentifier: "HTClassDesCell", for: indexPath) as! HTClassDesCell
            cell.BLOCK_premiumBLOCK = { [weak self] in
                if self?.var_selectedProductid.isEmpty == true {
                    //未选择
                    return
                }
                //已订阅
                let var_purchaseInfo = HTClassStorage.ht_getPurchaseInfo()
                if var_purchaseInfo?.var_productId == self?.var_selectedProductid {
                    HTClassHudView().ht_showToastOnView(var_view: self!.view, var_title: "You have subscribed to the product!", var_completedBlock: nil).hide(animated: true, afterDelay: var_kHudHiddenTime)

                    return
                }
                //订阅
                let var_hud = HTClassHudView().ht_showLoadingOnView(var_view: self!.view, var_completedBlock: nil)
                var_HTClassPayManagerInstance.ht_requestProduct(var_productId: self?.var_selectedProductid ?? "") { [weak self] var_isSuccess, var_isCancel, var_msg, var_purchaseInfo in
                    DispatchQueue.main.async {
                        var_hud.hide(animated: true, afterDelay: var_kHudHiddenTime)
                        if var_isSuccess {
                            HTClassHudView().ht_showToastOnView(var_view: self!.view, var_title: var_msg, var_completedBlock: nil).hide(animated: true, afterDelay: var_kHudHiddenTime)
                        }else{
                            if var_isCancel == false{
                                HTClassHudView().ht_showToastOnView(var_view: self!.view, var_title: var_msg, var_completedBlock: nil).hide(animated: true, afterDelay: var_kHudHiddenTime)
                            }
                        }
                        //刷新订阅信息
                        self?.ht_reloadPurchaseInfo()
                        //移除监听
                        var_HTClassPayManagerInstance.var_payResultBlock = nil
                    }
                }
            }
            cell.BLOCK_webClickBLOCK = {[weak self] var_url in
                let var_web = HTClassWebVC()
                var_web.var_url = var_url
                self?.navigationController?.pushViewController(var_web, animated: true)
            }
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.section > var_dataSource.count - 1 {
            return
        }
        let var_model = var_dataSource[indexPath.section]
        var_selectedProductid = var_model.var_productId
        tableView.reloadData()
    }
}
